package com.hangsu.train.heatbeat;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Server {

    private static Server server=null;

    private Server() {

    }

    public static synchronized Server  getInstance(){
        if(server==null){
            server=new Server();
        }
        return server;
    }

    private static final Map<String, Long> lastHeartbeatTime = new ConcurrentHashMap<>();

    public void start() {
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() ->
                lastHeartbeatTime.entrySet().removeIf(entry -> System.currentTimeMillis() - entry.getValue() > 3000
                ), 5, 1, TimeUnit.SECONDS);
    }

    public boolean contains(String servialNumber) {
        return lastHeartbeatTime.containsKey(servialNumber);
    }

    public void ping(String servialNumber) {
        lastHeartbeatTime.put(servialNumber, System.currentTimeMillis());
    }
}
